package cn.kgc.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/11/21
 * @description   shiro授权操作   前提   必须是认证通过的用户
 */
public class ShiroAuthorizationInfo {


    public static void main(String[] args) {


        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);
        defaultSecurityManager.setRealm(customerRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("tom", "123456");

        subject.login(token);



        //   用户认证通过    授权
        System.out.println("=================用户认证通过,开始用户授权操作===============");
        //  基于角色进行权限的判定
        // boolean b = subject.hasRole("super");
        List<String> roles = Arrays.asList("customer", "root", "super");
        boolean b  =   subject.hasAllRoles(roles);

        if (b){
            System.out.println("已完成相关操作");
        }else {
            System.out.println("没有操作权限，请联系管理员");
        }


        // 基于权限字符串 实现权限的控制  user  CRUD  sys:user:select  sys:user:update  sys:user:delete  sys:user:add
        boolean permitted = subject.isPermitted("sys:user:add");
        System.out.println("permitted = " + permitted);

    }

}
